from flask import Blueprint, request, jsonify, current_app
from werkzeug.utils import secure_filename
import os
from datetime import datetime
from ..utils import member_login_required, get_current_member
from inc.models import db, ProjectAttachment, JiraProject
import uuid

attachment_bp = Blueprint('attachment', __name__)

def allowed_file(filename):
    ALLOWED_EXTENSIONS = {'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'jpg', 'jpeg', 'png', 'gif', 'zip', 'rar'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@attachment_bp.route('/upload/<int:project_id>', methods=['POST'])
@member_login_required
def upload_file(project_id):
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'}), 400

    if not allowed_file(file.filename):
        return jsonify({'error': 'File type not allowed'}), 400

    # 验证项目存在且用户有权限
    project = JiraProject.query.get_or_404(project_id)
    current_member = get_current_member()
    if current_member.id not in [m.member_id for m in project.members] and current_member.id != project.owner_id:
        return jsonify({'error': 'No permission'}), 403

    # 创建上传目录
    upload_dir = os.path.join(current_app.config['UPLOAD_FOLDER'], str(project_id))
    os.makedirs(upload_dir, exist_ok=True)

    # 生成唯一文件名
    filename = secure_filename(file.filename)
    unique_id = uuid.uuid4().hex[:8]
    new_filename = f"{unique_id}_{filename}"
    filepath = os.path.join(upload_dir, new_filename)

    # 保存文件
    file.save(filepath)

    # 保存到数据库
    attachment = ProjectAttachment(
        project_id=project_id,
        uploader_id=current_member.id,
        filename=filename,
        filepath=filepath,
        filesize=os.path.getsize(filepath),
        filetype=file.content_type,
        description=request.form.get('description', '')
    )
    db.session.add(attachment)
    db.session.commit()

    return jsonify({
        'id': attachment.id,
        'filename': filename,
        'filepath': filepath,
        'uploader': current_member.name,
        'created_at': attachment.created_at.isoformat()
    }), 201